package com.bianpai.core;

import com.bianpai.execution.ExecutionStrategy;
import com.bianpai.execution.SequentialExecutionStrategy;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 业务流程，由多个节点组成
 */
public class Flow {
    private String id;
    private String name;
    private String description;
    private List<Node> nodes;
    private Map<String, List<String>> dependencies; // 节点依赖关系
    private ExecutionStrategy executionStrategy;
    
    public Flow(String id, String name) {
        this.id = id;
        this.name = name;
        this.nodes = new ArrayList<>();
        this.dependencies = new HashMap<>();
        this.executionStrategy = new SequentialExecutionStrategy(); // 默认使用顺序执行策略
    }
    
    public String getId() {
        return id;
    }
    
    public String getName() {
        return name;
    }
    
    public void setDescription(String description) {
        this.description = description;
    }
    
    public String getDescription() {
        return description;
    }
    
    /**
     * 添加节点
     * @param node 节点
     * @return 当前流程实例，支持链式调用
     */
    public Flow addNode(Node node) {
        nodes.add(node);
        return this;
    }
    
    /**
     * 添加节点依赖关系
     * @param nodeId 当前节点ID
     * @param dependsOnNodeId 依赖的节点ID
     * @return 当前流程实例，支持链式调用
     */
    public Flow addDependency(String nodeId, String dependsOnNodeId) {
        dependencies.computeIfAbsent(nodeId, k -> new ArrayList<>()).add(dependsOnNodeId);
        return this;
    }
    
    /**
     * 设置执行策略
     * @param executionStrategy 执行策略
     * @return 当前流程实例，支持链式调用
     */
    public Flow setExecutionStrategy(ExecutionStrategy executionStrategy) {
        this.executionStrategy = executionStrategy;
        return this;
    }
    
    public List<Node> getNodes() {
        return nodes;
    }
    
    public Map<String, List<String>> getDependencies() {
        return dependencies;
    }
    
    public ExecutionStrategy getExecutionStrategy() {
        return executionStrategy;
    }
    
    /**
     * 获取指定节点的所有依赖节点
     * @param nodeId 节点ID
     * @return 依赖节点ID列表
     */
    public List<String> getDependenciesForNode(String nodeId) {
        return dependencies.getOrDefault(nodeId, new ArrayList<>());
    }
    
    /**
     * 根据ID查找节点
     * @param nodeId 节点ID
     * @return 节点对象，如果不存在则返回null
     */
    public Node getNodeById(String nodeId) {
        return nodes.stream()
                .filter(node -> node.getId().equals(nodeId))
                .findFirst()
                .orElse(null);
    }
}